package com.woniuxy.cloud.areaassembly.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniuxy.cloud.areaassembly.entity.SysArea;
import com.woniuxy.cloud.areaassembly.mapper.SysAreaMapper;
import com.woniuxy.cloud.areaApi.dto.AreaDto;
import com.woniuxy.cloud.areaassembly.exception.AreaException;
import com.woniuxy.cloud.areaassembly.service.SysAreaService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.cloud.areaassembly.util.WoniuBeanUtils;
import com.woniuxy.cloud.areaApi.param.initiationAreaParam;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 周川雄
 * @since 2022-02-18
 */
@Service
public class SysAreaServiceImpl extends ServiceImpl<SysAreaMapper, SysArea> implements SysAreaService {

    @Override
    public List<AreaDto> listArea(Integer areaId, QueryWrapper<SysArea> queryWrapper) {
        List<SysArea> list = new ArrayList<>();

        if (queryWrapper == null) {
            queryWrapper = new QueryWrapper<SysArea>();
        }


        if (0 == areaId) {
            list = list(queryWrapper);
            return WoniuBeanUtils.copyList(list, AreaDto.class);
        }


        SysArea area = getById(areaId);

        if (StringUtils.isEmpty(area)) throw new AreaException("区域id错误，无区域存在", 10500);

        Integer level = area.getAreaLevel();
        if (level == 1) {
            list = this.baseMapper.selectAreaLevel1(areaId, queryWrapper);
        } else if (level == 2) {
            list = this.baseMapper.selectAreaLevel2(areaId, queryWrapper);
        } else if (level == 3) {
            list.add(area);
        }
        return WoniuBeanUtils.copyList(list, AreaDto.class);
    }

    @GlobalTransactional
    @Override
    public boolean initiationArea(initiationAreaParam param) {
        //1开启权限,0关闭权限
        if (param.getStatus() == 1) {
            if (0 != param.getAreaId()) {
                SysArea area = getById(param.getAreaId());
                if (StringUtils.isEmpty(area)) throw new AreaException("区域id错误，无区域存在", 10502);
                Integer level = area.getAreaLevel();
                if (level == 2 || level == 3) {
                    SysArea one = getOne(new QueryWrapper<SysArea>().eq("id", area.getAreaParentId()));
                    if (one.getIsInitiation() == 0) throw new AreaException("请先勾选上级城市" + one.getAreaName(), 10501);
                }
            }
        }


        List<AreaDto> dtos = listArea(param.getAreaId(), null);
        List<SysArea> areas = WoniuBeanUtils.copyList(dtos, SysArea.class);
        for (SysArea area : areas) {
            area.setIsInitiation(param.getStatus());
        }

        return updateBatchById(areas);
    }
}
